package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.*;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.service.IProductService;
import cn.wolfcode.shop.service.IProductSkuService;
import cn.wolfcode.shop.service.IShopCarService;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.MessageFormat;

/**
 * Created by wolfcode on 2018/8/20.
 */
@Service
public class ShopCarServiceImpl implements IShopCarService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductSkuService productSkuService;
    public ShopCar addShopCar(String token, Long productSkuId, BigDecimal number) {
        String userKey = MessageFormat.format(RedisConstants.USER_LOGIN_TOKEN,token);
        UserLogin userLogin = (UserLogin) redisTemplate.opsForValue().get(userKey);
        if(userLogin==null){
            throw new UserException("登录信息过期.");
        }
        String shopCarKey = MessageFormat.format(RedisConstants.USER_SHOP_CAR,userLogin.getId(),productSkuId);
        ShopCar shopCar = (ShopCar) redisTemplate.opsForValue().get(shopCarKey);
        if(shopCar==null){
            //在购物车中并没有该商品
            shopCar = new ShopCar();
            ProductSku productSku = productSkuService.get(productSkuId);
            Product product = productService.getProductById(productSku.getProductId());
            shopCar.setProductName(product.getName());
            shopCar.setProductImage(product.getImage());
            shopCar.setProductPrice(productSku.getPrice());
            shopCar.setProductSkuId(productSkuId);
            shopCar.setNumber(number);
            StringBuilder productSkuStringBuilder = new StringBuilder(50);
            for(ProductSkuProperty psp:productSku.getProductSkuPropertyList()){
                productSkuStringBuilder.append(psp.getSkuProperty().getName()).append(":").append(psp.getValue()).append(" ");
            }
            shopCar.setProductSkuPropertyStr(productSkuStringBuilder.toString());
        }else{
            //已经有该商品了.
            shopCar.setNumber(shopCar.getNumber().add(number));
        }
        redisTemplate.opsForValue().set(shopCarKey,shopCar);
        return shopCar;
    }
}
